package com.cj.webapp.common.sign;

import com.cj.framework.core.exception.ApplicationException;
import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.net.URL;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;


public class CertSign {
	
	/**
     * 签名处理
     * @param prikey 私钥
     * @param origin 签名源内容
     * @return
     */
	public static String makeSign(String prikey, String origin) {
		try
        {
        	PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(XBase64.getBytesBASE64(prikey));
            KeyFactory keyf = KeyFactory.getInstance("RSA");
            PrivateKey myprikey = keyf.generatePrivate(priPKCS8);
            // 用私钥对信息生成数字签名
            java.security.Signature signet = java.security.Signature.getInstance("MD5withRSA");
            signet.initSign(myprikey);
            signet.update(origin.getBytes("UTF-8"));
            // 对信息的数字签名
            byte[] signed = signet.sign(); 
            return new String(org.apache.commons.codec.binary.Base64.encodeBase64(signed));
        }catch(Exception ex){
        	throw new ApplicationException("MSG_0009");
		}
	}
	
	/**
     * 签名验证
     * @param pubkey 公钥
     * @param origin 源钥
     * @param signed 签名结果串
     * @return
     */
	public static boolean verifySign(String pubkey, String origin, String signed) {
		try
        {
            X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(XBase64.getBytesBASE64(pubkey));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey pubKey = keyFactory.generatePublic(bobPubKeySpec);
            // 这是SignatureData输出的数字签
            byte[] signBytes = XBase64.getBytesBASE64(signed);
            java.security.Signature signetcheck = java.security.Signature.getInstance("MD5withRSA");
            signetcheck.initVerify(pubKey);
            signetcheck.update(origin.getBytes("UTF-8"));
            return signetcheck.verify(signBytes);
        } catch(Exception ex){
			//throw new BasException(BasConstant.MSG_0011, new String[]{ex.getMessage()});
        	throw new ApplicationException("MSG_0009");
		}
	}
	
	/**
	 * 获取摘要信息
	 * @param src 原始字符串信息 
	 * @return
	 */
	public static String getOriginSummary(String src) {
		StringBuffer sb = new StringBuffer();
	    String part = "";
	    try {
	    	MessageDigest md = MessageDigest.getInstance("MD5");
	        byte[] md5 = md.digest(src.getBytes("UTF-8"));
	        for (int i = 0; i < md5.length; i++) {
	        	part = Integer.toHexString(md5[i] & 0xFF);
	        	if (part.length() == 1) {
	        		part = "0" + part;
	        	}
	        	sb.append(part);
	        }
	    } catch (Exception ex) {
	    	return "";
	    }
	    return sb.toString();
	}
	
	/**
     * 获取钥匙文件内容
     * @param fileName 钥匙文件
     * @return 钥匙内容
     */
	public static String getKeyContent(String fileName) {
		StringBuffer priBuffer = new StringBuffer();
		try
		{
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
			String msg = null;
			while((msg = br.readLine())!= null)   
			{
				if (msg.indexOf("-----BEGIN")==-1 && msg.indexOf("-----END")==-1) {
					priBuffer.append(msg);
				}				
			}
			br.close();
		}catch(Exception ex) {
			//throw new BasException(BasConstant.MSG_0014, new String[]{ex.getMessage()});
			ex.printStackTrace();
			throw new ApplicationException("MSG_0009");
		}
		if (StringUtils.isBlank(priBuffer.toString())) {
			//throw new BasException(BasConstant.MSG_0014, new String[]{"文件内容为空"});
			throw new ApplicationException("MSG_0009");
		}else{
			return priBuffer.toString();
		}
	}
	
	/**
     * 获取当前文件的主路径
     * @return 路径
     */
	public static String getSysPath() {
		String deployWarPath = StringUtils.EMPTY;
		FileInputStream propStream = null;
		try
		{
			URL url = CertSign.class.getResource("CertSign.class");
	        String temppath = url.toString();
	        int startIndex = temppath.indexOf("file:");
	        //updated by renjiayue 20161220 更改配置文件查找方式 begin
	        int index = temppath.indexOf("classes");
	        deployWarPath = temppath.substring(startIndex + "file:".length() + 1, index);
	        deployWarPath += "classes/";
	      //updated by renjiayue 20161220 end
	        // 如果是linux的操作系统,并且开始没有file分隔符的话,那么要加上
	        if (System.getProperty("os.name").indexOf("Linux") != -1) {
	            if (!deployWarPath.startsWith(File.separator)) {
	                deployWarPath = File.separator + deployWarPath;
	            }
	        }
		}catch(Exception ex){
			
		}finally{
			if (propStream!=null) {
				try {
					propStream.close();
				} catch (IOException e) {
				}
			}				
		}
		return deployWarPath;
	}
}
